package com.system.weirdor.facade.shiro.realm;

import com.system.weirdor.facade.provider.RoleFacadeApi;
import com.system.weirdor.facade.provider.UserFacadeApi;
import com.system.weirdor.facade.shiro.vo.ShiroUser;
import com.system.weirdor.module.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * Created by weirdor on 2017/8/24.
 */
@Component
public class ShiroDbRealm extends AuthorizingRealm {


    @Autowired
   private UserFacadeApi userFacadeApi;

    @Autowired
    private RoleFacadeApi roleFacadeApi;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("______________doget______________");
        ShiroUser shiroUser= (ShiroUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //用户角色
        Set<String> rolesSet = roleFacadeApi.listUserRoles(shiroUser.getId());
        //用户权限
        Set<String> permsSet = roleFacadeApi.listUserPerms(shiroUser.getId());
        info.setRoles(rolesSet);
        info.setStringPermissions(permsSet);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        System.out.println(token.getCredentials());
        User userInfo = userFacadeApi.selectByUserName(username);
        if(userInfo == null){
            return null;
        }
        if (userInfo.getStatus() == 1) {
            return null;
        }
        ShiroUser shiroUser=new ShiroUser();
        shiroUser.setShowName(StringUtils.isBlank(userInfo.getUsername()) ? userInfo.getLoginName() : userInfo.getUsername());
        shiroUser.setRealName(userInfo.getUsername());
        shiroUser.setId(userInfo.getUserId());
        shiroUser.setHealUrl(userInfo.getHeadUrl());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                shiroUser,
                userInfo.getPassword(),
                ByteSource.Util.bytes(userInfo.getSalt()),
                getName()  //realm name
        );
        this.setSession("userSession", shiroUser);
        this.setSession("userSessionId", shiroUser.getId());
        return authenticationInfo;
    }

    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }

    /**
     * 清除用户缓存
     * @param shiroUser
     */
    public void removeUserCache(ShiroUser shiroUser){
        removeUserCache(shiroUser.getShowName());
    }

    /**
     * 清除用户缓存
     * @param loginName
     */
    public void removeUserCache(String loginName){
        SimplePrincipalCollection principals = new SimplePrincipalCollection();
        principals.add(loginName, super.getName());
        super.clearCachedAuthenticationInfo(principals);
    }
}
